﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using CefSharp;
using CefSharp.WinForms;
using JPCloudPrinter.Utils;
using log4net;

namespace JPCloudPrinter {
    public partial class FrmMain2 : CCSkinMain {
        private ILog logger = LogManager.GetLogger("root");

        public FrmMain2()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //初始化窗口出现位置
            Point p = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width - 50, (Screen.PrimaryScreen.WorkingArea.Height - this.Height)/2);
            this.PointToScreen(p);
            this.Location = p;

            ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ShowInformation),null);

            var browser = new ChromiumWebBrowser("http://localhost:3030/")
            {
                Dock = DockStyle.Fill,
            };

            toolStripContainer1.ContentPanel.Controls.Add(browser);

            browser.ConsoleMessage += OnBrowserConsoleMessage;

            PrinterObject printerObject = new PrinterObject();
            printerObject.PrintDocumentEvent += printerObject_PrintDocumentEvent;

            browser.RegisterJsObject("printerObject", printerObject);
        }

        void printerObject_PrintDocumentEvent(Dictionary<string, object> dict)
        {
            MessageBox.Show("正在打印" + dict["fileName"] + ",纸张大小：" + dict["pageSize"] + ",份数：" + dict["quantity"]);
        }

        private void OnBrowserConsoleMessage(object sender, ConsoleMessageEventArgs args)
        {
            logger.Warn(string.Format("Line: {0}, Source: {1}, Message: {2}", args.Line, args.Source, args.Message));
        }

        private void ShowInformation(object obj)
        {
            Thread.Sleep(2000);

            this.Invoke(new MethodInvoker(()=>
            {
                FrmInformation frm = new FrmInformation("通知");
                frm.Show(this);
            }));
        }

        private void FrmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            //显示主窗体
            this.Visible = true;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
            //隐藏托盘图标
            this.notifyIcon1.Visible = false;
            this.Show();
        }
    }
}
